package cn.techcave.demo.jpa3.service

import cn.techcave.demo.jpa3.domain.Record
import cn.techcave.demo.jpa3.repository.RecordRepo
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.time.LocalDate
import javax.persistence.criteria.CriteriaBuilder
import javax.persistence.criteria.Root
import org.springframework.data.jpa.domain.Specification
import org.springframework.data.jpa.domain.Specifications.where
import javax.persistence.criteria.CriteriaQuery
import javax.persistence.criteria.Predicate


@Service
class RecordService {
    @Autowired
    lateinit var recordRepo: RecordRepo

    fun nameLike(name:String): Specification<Record> {
        return object : Specification<Record> {
            override fun toPredicate(root: Root<Record>, query: CriteriaQuery<*>,
                                     builder: CriteriaBuilder): Predicate {
                return builder.like(root.get("name"),"%$name%")
            }
        }
    }

    fun filterByName(name:String) = recordRepo.findAll(nameLike(name))

    fun filterByNames(n1:String, n2:String) :List<Record> {
        return recordRepo.findAll(where(nameLike(n1)).or(nameLike(n2)))
    }
    fun findAll() = recordRepo.findAll()
}